package com.hxzy.util.easyexcel.convert;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.hxzy.common.annon.DictTypeAnnon;
import com.hxzy.common.util.SpringBeanFactoryUtil;
import com.hxzy.entity.SysDictData;
import com.hxzy.util.DictCacheUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Optional;

/**
 * @Desc excel状态转换
 * @Author: admin
 * @Date: 2023/07/06/10:39
 */
public class DictTypeConvert implements Converter<String> {


    /**
     * java数据类型
     * @return
     */
    @Override
    public Class<?> supportJavaTypeKey() {
        return String.class;
    }

    /**
     * excel单元格的数据类型
     *
     * @return
     */
    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return  CellDataTypeEnum.STRING;
    }



    @Override
    public WriteCellData<?> convertToExcelData(String value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        //要替换的值
        String replaceValue = value;
        //当前excel转换字段
        Field field = contentProperty.getField();
        //字段上面是否有我们自定义的注解 (反射)
        DictTypeAnnon declaredAnnotation = field.getDeclaredAnnotation(DictTypeAnnon.class);
        //有自定义注解
        if (declaredAnnotation != null) {
            //手动的获取spring容器管理的对象
            DictCacheUtil dictCacheUtil = SpringBeanFactoryUtil.getBean("dictCacheUtil", DictCacheUtil.class);
            String dictType = declaredAnnotation.value().name();
            //去redis中查询相应缓存数据
            List<SysDictData> dictDataList = dictCacheUtil.findByDictType(dictType);
            //如果有值
            if (dictDataList != null && dictDataList.size() > 0) {
                Optional<SysDictData> optional =dictDataList.stream()
                        .filter(p -> p.getDictValue().equals(value)).findFirst();
                if (optional.isPresent()) {
                    replaceValue = optional.get().getDictLabel();
                }
            }
        }

        return new WriteCellData<String>(replaceValue);
    }
}
